/* $Id: SyncService.java 86 2007-12-20 22:56:41Z osborn.steven $
 * 
 * Undroid Package Manager
 *
 * Copyright 2007 Steven Osborn
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */
package com.bitsetters.undroid;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;

/**
 * 
 * @author Steven Osborn - http://steven.bitsetters.com
 */
public class SyncService extends Service implements Runnable {
    
    private NotificationManager mNM;
    private Intent mInvokeIntent;
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;

    
    /**
     * 
     */
    @Override
    protected void onCreate() {
	
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.
        Thread thr = new Thread(null, this, "SyncService");
        thr.start();
    }

    /**
     * 
     */
    @Override
    protected void onStart(int startId, Bundle arguments) {
	
        System.out.println("Starting #" + startId + ": " + arguments);
        while (mServiceHandler == null) {
            synchronized (this) {
                try {
                    wait(100);
                } catch (InterruptedException e) {
                }
            }
        }

        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = arguments;
        mServiceHandler.sendMessage(msg);
        Log.i("ServiceStartArguments", "Sending: " + msg);
    }

    /**
     * 
     */
    @Override
    protected void onDestroy() {
	
        while (mServiceLooper == null) {
            synchronized (this) {
                try {
                    wait(100);
                } catch (InterruptedException e) {
                }
            }
        }
        mServiceLooper.quit();

        // Cancel the persistent notification.
        mNM.cancel(R.string.sync_started);

        // Tell the user we stopped.
        mNM.notifyWithText(R.string.sync_stopped,
                   getText(R.string.sync_stopped),
                   NotificationManager.LENGTH_SHORT,
                   null);
    }

    /**
     * 
     */
    public void run() {
	
        Looper.prepare();

        mServiceLooper = Looper.myLooper();
        mServiceHandler = new ServiceHandler();

        Looper.loop();
    }

    /**
     * 
     */
    @Override
    public IBinder getBinder() {
        return null;
    }

    /**
     * 
     *
     */
    private final class ServiceHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            
            Bundle arguments = (Bundle)msg.obj;
            String txt = getResources()
                    .getString(R.string.sync_started);
            txt = txt + arguments.getString("name");

            Log.i("ServiceStartArguments", "Message: " + msg + ", " + txt);

            // Display a notification about us starting.  We use both a transient
            // notification and a persistent notification in the status bar.
            mNM.notifyWithText(R.string.sync_started,
                       txt,
                       NotificationManager.LENGTH_SHORT,
                       new Notification(
                           R.drawable.accessibility22,
                           getText(R.string.sync_started),
                           mInvokeIntent,
                           null,
                           null));

            // Normally we would do some work here...  for our sample, we will
            // just sleep for 10 seconds.
            long endTime = System.currentTimeMillis() + 5*1000;
            while (System.currentTimeMillis() < endTime) {
                synchronized (this) {
                    try {
                        wait(endTime - System.currentTimeMillis());
                    } catch (Exception e) {
                    }
                }
            }

            Log.i("ServiceStartArguments", "Done with #" + msg.arg1);
            stopSelf(msg.arg1);
        }

    };

}